<?php
/**
 * Notice_Sysnotice
 */
class Notice_Sysnotice
{
	private $_title,$_message,$_to,$de;
	private $_city_id;
	CONST _CONST_TB_SYSNOTICE_ = 'sysnotice_list';

	public function title($title)
	{
		$this->_title = (string) $title;
		return $this;
	}

	public function message($message)
	{
		$this->_message = (string) $message;
		return $this;
	}

	public function to($to)
	{
		$this->_to = $to;
		return $this;
	}

	public function de($de)
	{
		$this->_de =  $de;
		return $this;
	}
	
	public function send($city_id)
	{
		$this->_city_id = $city_id;
		if(empty($this->_to)&& empty($this->_de))
		{
		  $this->add();
		}
		if($this->_de)
		{
		  $this->del();
		}
		if($this->_to && empty($this->_de))
		{
		  $this->edit();
		} 
		
	}
	/**
	 * 删除公告信息
	 *
	 */
	private function del()
	{
		$query = DB::delete(self::_CONST_TB_SYSNOTICE_)
		->where('id','=',$this->_de)
		->limit(1)
		->execute();
		return empty($query) ? false : true;
	}
    /**
	 * 编辑公告信息
	 *
	 */
    private function edit()
	{
	  $uid   = User::current_user_id();	
      $query = DB::update(self::_CONST_TB_SYSNOTICE_)
		     ->set(array('title'=>$this->_title,'content'=>$this->_message,'uid'=>$uid,'time'=>time()))
			 ->where('id','=',$this->_to)
			 ->limit(1)
			 ->execute();
	  return empty($query) ? false : true;
	}
    /**
	 * 添加公告信息
	 *
	 */
	private function add()
	{
	   $uid  = User::current_user_id();	
	   $data = array(
	    	'title'   => $this->_title,
			'content' => $this->_message,
            'uid'     => $uid,
			'time'    => time(),
			'cityid'  => $this->_city_id, 
       );
	   $query = DB::insert(self::_CONST_TB_SYSNOTICE_)
		      ->columns(array('title','content','uid','time','cityid'))  
		      ->values($data)
			  ->execute();
	   if($query)
	   {
	      $back = $query;
	   }
	   else
	   {
	      $back = '';
	   }
	   return $back;
	}
    /**
	 *  根据城市id获取2条公告信息
	 *
	 *
	 */
	public function lists ($city_id)
	{
		$query = DB::select('id','title','content','uid','time','cityid')
			   ->from(self::_CONST_TB_SYSNOTICE_)
			   ->where('cityid','=',$city_id)
			   ->limit(2)
			   ->order_by('id','asc')
			   ->execute()
			   ->as_array();
		if($query)
		{
		  $back = $query;
		}
		else
		{
		  $back = array();
		}
		return $back;
	}
    /**
	 *  根据公告id获取公告详细信息
	 *  
	 */
     public function detail($notice_id)
	 {
		$query = DB::select('title','content','cityid','time')
			   ->from(self::_CONST_TB_SYSNOTICE_)
			   ->where('id','=',$notice_id)
			   ->limit(1)
			   ->execute()
			   ->as_array();
		$detail = array();
		if($query)
		{
		   $detail = $query[0];
		}
		return $detail;
	 }
} 
